from pyhanlp import *
import re


class Recognizer:
    MODEL = "model.bin"
    # 分词器
    PerceptronSegmenter = JClass(
        "com.hankcs.hanlp.model.perceptron.PerceptronSegmenter"
    )
    # 词性标注器
    PerceptronPOSTagger = JClass(
        "com.hankcs.hanlp.model.perceptron.PerceptronPOSTagger"
    )
    # 命名实体识别器
    PerceptronNERecognizer = JClass(
        "com.hankcs.hanlp.model.perceptron.PerceptronNERecognizer"
    )

    # 初始化分析工具
    def __init__(self) -> None:
        self.recognizer = self.PerceptronNERecognizer(self.MODEL)
        self.analyzer = PerceptronLexicalAnalyzer(
            self.PerceptronSegmenter(), self.PerceptronPOSTagger(), self.recognizer
        )

    def analyse(self, string) -> list:
        result = self.analyzer.analyze(string).toString()
        # 取出单独成词的名词短语
        single_none_re = re.compile(r"([^/[\s]{5,15})/n\w")
        single_none_list = single_none_re.findall(result)
        # 去除标签
        result = re.sub(r"/\w{1,3}", "", result)
        result = re.sub(r"\s", "", result)
        # 取出由方括号包含的名词短语
        none_re = re.compile(r"\[(.*?)\]")
        print(single_none_list + none_re.findall(result))
        return single_none_list + none_re.findall(result)
